package com.cyz.user.job;

import com.cyz.common.bean.Card;
import com.cyz.user.userService.CardService;
import com.cyz.common.utils.MyRedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

//    @Autowired
//    private RedisUtil redisUtil;
    @Autowired
    private MyRedisUtil myRedisUtil;

    @Autowired
    private CardService cardService;

    @Scheduled(cron = "0/10 * * * * ? ")
    public void updateViewCount(){

        System.out.println("更新浏览量任务执行");
//        获取redis中的浏览量
//        Map<String, Integer> viewCountMap = redisUtil.getCacheMap("card:viewCount");
        Map<String, Object> viewCountMap = myRedisUtil.myHashEntries("card:viewCount");
//        System.out.println(cacheMap.entrySet());
//        Set<Map.Entry<String, Integer>> entries = cacheMap.entrySet();
//        entries.forEach(item->{
////            System.out.println(item.getKey());
//            Integer value = Integer.parseInt(String.valueOf(item.getValue()));
//            System.out.println(value);
//            System.out.println(item.getValue());
//            System.out.println(key);
//            System.out.println(value);
//            System.out.println(key+":"+value.toString());
//        });
//

//        List<Card> cards = new ArrayList<>();
//        cards.add(new Card("1",2));
//        cards.add(new Card("2",2));
//
//        cards = cards.stream().collect(Collectors.toList());

         List<Card> cards = new ArrayList<>();
         viewCountMap.entrySet()
                 .stream()
                 .map(item -> {
                     Card card = new Card();
                     card.setId(Integer.parseInt(item.getKey()));
                     card.setViewCount((Integer) item.getValue());
                     return card;
                 })
                 .collect(Collectors.toList());
//        collect.add(new CardViewCountDto(key, value))
//        List<Card> cards = BeanCopyUtil.copyBeanList(collect, Card.class);

//        更新到数据库中
//        cards.forEach(card ->{
//            cardService.updateById(card);
//        });
//        Card card = new Card();
//        card.setId(1);
//        card.setViewCount(2);
//        cardService.updateById(card);
        cardService.updateBatchById(cards);
    }
}

